// /chat-messages
import axios, {appHeaders} from "../utils/axios"
import {EventSourcePolyfill} from 'event-source-polyfill';

class ChatApi {
    constructor() {
        this.sseStart = true
        this.backData = null
    }

    async sendMessage(query, options = {}, backFn) {
        try {
            this.sseStart = true
            this.backData = backFn
            let params = {
                "response_mode": "streaming",
                "conversation_id": "5f248dad-304a-4b15-8c01-e58f73177b70",
                "files": [],
                "query": query,
                "inputs": {},
                "parent_message_id": "e713ab17-5d43-49ee-b3f7-5000500060e0"
            }
            let chatBaseURL = "/api/chat-messages"
            fetch(chatBaseURL, {
                method: 'POST', // 或 'POST'
                body: JSON.stringify(params),
                timeout: 0,
                dataType: "text/event-stream",
                headers: {
                    // 'Accept': 'text/event-stream',
                    // 'Content-Type': 'text/event-stream',
                    // 'Cache-Control': 'no-cache',
                    'Content-Type': 'application/json',
                    ...appHeaders
                },
                // keepalive: true, // 保持连接
            }).then(response => {
                console.log("response======", response)
                if (!response.ok || !response.body) {
                    throw new Error('SSE连接失败');
                }
                return response
            }).then(async response => {
                const reader = response.body.getReader();
                console.log("reader=======", reader)
                const decoder = new TextDecoder();
                while (this.sseStart) {
                    console.time("reader")
                    const {done, value} = await reader.read();
                    console.timeEnd("reader")
                    console.log("while=========done", done)
                    console.log("while=========value", value)
                    if (done) {
                        this.sseStart = false
                        break;
                    }
                    const chunk = decoder.decode(value, {stream: true});
                    this.processSSEChunk(chunk);
                }
            })
        } catch (error) {
            console.error('SSE错误:', error);
        }
    }

    processSSEChunk(chunk) {
        // 处理SSE格式数据
        const lines = chunk.split('\n');
        let event = {data: '', event: 'message', id: null};

        for (const line of lines) {
            if (line.startsWith('event:')) {
                event.event = line.replace('event:', '').trim();
            } else if (line.startsWith('data:')) {
                event.data += line.replace('data:', '').trim() + '\n';
            } else if (line.startsWith('id:')) {
                event.id = line.replace('id:', '').trim();
            } else if (line === '') {
                // 空行表示事件结束
                if (event.data) {
                    const data = event.data.trim();
                    try {
                        const parsedData = JSON.parse(data);
                        this.dispatchEvent(new CustomEvent(event.event, {detail: parsedData}));
                    } catch {
                        this.dispatchEvent(new CustomEvent(event.event, {detail: data}));
                    }
                }
                event = {data: '', event: 'message', id: null};
            }
        }
    }

    dispatchEvent(data) {
        try {
            console.log("dispatchEvent", data);
            this.backData(data.detail);
            if (data.detail.event === "message_end") {
                // this.sseStart = false
            }
        } catch {
            this.backData(data.detail);
        }
    }


    getMessageHistory() {
        let params = {
            conversation_id: "5f248dad-304a-4b15-8c01-e58f73177b70",
            limit: 20,
            last_id: ""
        }
        return axios.get('/messages', {params})
    }
}

export const chatApi = new ChatApi();